<?php

declare(strict_types=1);
/**
 * This file is part of Hyperf.
 *
 * @link     https://www.hyperf.io
 * @document https://hyperf.wiki
 * @contact  group@hyperf.io
 * @license  https://github.com/hyperf/hyperf/blob/master/LICENSE
 */

namespace App\Controller;

use App\Logic\LiveLogic;
use App\Logic\MatchLogic;
use App\Middleware\AuthMiddleware;
use App\Model\Live;
use App\Utils\Enum\LiveEnum;
use Exception;
use Hyperf\Context\Context;
use Hyperf\HttpServer\Annotation\AutoController;
use Hyperf\HttpServer\Annotation\Middleware;
use Psr\Http\Message\ResponseInterface;

#[AutoController]
class LiveController extends AbstractController
{
    /**
     * 直播概况
     * @return ResponseInterface
     * @throws Exception
     */
    #[Middleware(AuthMiddleware::class)]
    public function overview(): ResponseInterface
    {
        $userid = Context::get('userid', 0);
        $data = LiveLogic::overview($userid);
        return $this->apiReturn(200, 'succ', $data);
    }

    /**
     * 获取房间配置
     * @return ResponseInterface
     */
    #[Middleware(AuthMiddleware::class)]
    public function liveInfo(): ResponseInterface
    {
        $userId = Context::get('userid', 0);
        $data = LiveLogic::getRoomInfo($userId);
        return $this->apiReturn(200, 'succ', $data);
    }

    /**
     * 设置房间
     * @return ResponseInterface
     */
    #[Middleware(AuthMiddleware::class)]
    public function liveSet(): ResponseInterface
    {
        $userId = Context::get('userid', 0);
        $input = $this->request->all();
        try {
            LiveLogic::setRoomInfo($userId, $input);
            return $this->apiReturn(200, '保存成功');
        } catch (Exception $e) {
            return $this->apiReturn(400, $e->getMessage());
        }
    }

    /**
     * 主播获取直播记录.
     */
    #[Middleware(AuthMiddleware::class)]
    public function liveRecords(): ResponseInterface
    {
        $userid = Context::set('userid', 0);
        $input = $this->request->all();
        $data = LiveLogic::getRecord($userid, $input);
        return $this->apiReturn(200, 'succ', $data);
    }

    /**
     * 直播记录详情.
     */
    public function liveRecordDetail(): ResponseInterface
    {
        return $this->apiReturn(200, '操作成功', []);
    }

    /**
     * 主播开启直播.
     */
    #[Middleware(AuthMiddleware::class)]
    public function startLive(): ResponseInterface
    {
        $userid = Context::get('userid', 0);
        $input = $this->request->all();
        try {
            LiveLogic::startLive($userid, $input);
            return $this->apiReturn(200, '开启成功');
        } catch (Exception $e) {
            return $this->apiReturn(400, '开启失败:' . $e->getMessage());
        }
    }

    /**
     * 关播.
     */
    #[Middleware(AuthMiddleware::class)]
    public function closeLive(): ResponseInterface
    {
        $userid = Context::get('userid', 0);
        LiveLogic::closeLive($userid);
        return $this->apiReturn(200, '操作成功');
    }

    /**
     * 获取直播推流地址
     */
    public function getPushStreamAddress(): ResponseInterface
    {
        $userid = Context::get('userid', 0);
        try {
            $address = LiveLogic::getPushStreamAddress($userid);
            return $this->apiReturn(200, 'succ', ['address' => $address]);
        } catch (Exception $e) {
            return $this->apiReturn(400, '获取失败:' . $e->getMessage());
        }
    }

    /**
     * 获取可直播的比赛.
     */
    #[Middleware(AuthMiddleware::class)]
    public function loadMatchList(): ResponseInterface
    {
        $input = $this->request->all();
        if (!isset($input['query']['sportId']) || !intval($input['query']['sportId'])) {
            return $this->apiReturn(400, '请选择比赛类型');
        }
        $list = MatchLogic::getLiveMatchList($input);
        return $this->apiReturn(200, 'succ', $list);
    }

    /**
     * 发红包.
     */
    public function sendRedPacket()
    {
        // TODO
    }

    /**
     * 获取直播间管理员.
     */
    #[Middleware(AuthMiddleware::class)]
    public function getManager(): ResponseInterface
    {
        $userid = Context::get('userid');
        $roomId = $this->request->input('roomId', 0);
        if (!$roomId) {
            return $this->apiReturn(400, '参数错误');
        }
        $list = LiveLogic::getRoomManager($roomId);
        return $this->apiReturn(200, 'succ', $list);
    }

    /**
     * 设置直播间管理员.
     */
    #[Middleware(AuthMiddleware::class)]
    public function setManager(): ResponseInterface
    {
        $userid = Context::get('userid');
        $roomId = LiveLogic::getRoomId($userid);
        if (!$roomId) {
            return $this->apiReturn(400, '仅主播可设置房间管理员');
        }
        try {
            LiveLogic::setRoomManager($roomId, $userid);
            return $this->apiReturn(200, '设置成功');
        } catch (Exception $e) {
            return $this->apiReturn(400, $e->getMessage());
        }
    }

    /**
     * 主播/管理员(拉黑/释放)观众.
     */
    #[Middleware(AuthMiddleware::class)]
    public function blockUser(): ResponseInterface
    {
        $userid = Context::get('userid', 0);
        $input = $this->request->all();
        if (!$input['roomId'] || !$input['userid']) {
            return $this->apiReturn(400, '参数错误');
        }
        $isAnchor = LiveLogic::isRoomOwner($input['roomId'], $userid);
        if (!$isAnchor) {
            $isManager = LiveLogic::isRoomManager($input['roomId'], $userid);
        }
        if (!$isAnchor && !$isManager) {
            return $this->apiReturn(400, '无权执行该操作');
        }
        try {
            if ($input['op'] == LiveEnum::BLACKLIST_OP_TYPE_ADD) {
                LiveLogic::addBlackList($input['roomId'], $input['userid'], ['userid' => $userid, 'role' => $isAnchor ? LiveEnum::BLACKLIST_OP_ROLE_ANCHOR : LiveEnum::BLACKLIST_OP_ROLE_MANAGER]);
            } elseif ($input['op'] == LiveEnum::BLACKLIST_OP_TYPE_REM) {
                LiveLogic::removeBlackList($input['roomId'], $input['userid']);
            }
            return $this->apiReturn(200, '操作成功');
        } catch (Exception $e) {
            return $this->apiReturn(400, $e->getMessage());
        }
    }

    /**
     * 获取黑名单.
     */
    #[Middleware(AuthMiddleware::class)]
    public function getBlockList(): ResponseInterface
    {
        $userid = Context::get('userid', 0);
        $input = $this->request->all();
        if (!$input['roomId']) {
            return $this->apiReturn(400, '参数错误');
        }

        if (!LiveLogic::isRoomOwner($input['roomId'], $userid) && !LiveLogic::isRoomManager($input['roomId'], $userid)) {
            return $this->apiReturn(400, '无权获取该信息');
        }
        $data = LiveLogic::getBlackList($input['roomId'], $input);
        return $this->apiReturn(200, 'succ', $data);
    }

    /**
     * 获取礼物明细
     * @return ResponseInterface
     */
    #[Middleware(AuthMiddleware::class)]
    public function giftRecords(): ResponseInterface
    {
        $userId = Context::get('userid', 0);
        $input = $this->request->all();
        $roomId = Live::query()->where('userid', $userId)->value('room_id');
        $data = LiveLogic::getGiftRecords($roomId, $input);
        return $this->apiReturn(200, 'succ', $data);
    }
}
